package com.rockcent.mall.lib.helper;

import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.common.utils.DateUtils;
import com.rockcent.common.utils.RBeanUtils;
import com.rockcent.common.utils.RDateUtils;
import com.rockcent.common.utils.RequestUtils;
import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.domain.enumclass.CertifyType;
import com.rockcent.mall.lib.domain.enumclass.MallAuditCertifyInfoStatusType;
import com.rockcent.mall.lib.domain.enumclass.MerchantStatus;
import com.rockcent.mall.lib.domain.enumclass.SystemType;
import com.rockcent.mall.lib.dto.*;
import com.rockcent.mall.lib.repository.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.servlet.http.HttpServletRequest;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Created by HK on 16/8/16.
 */
public class BaseUserHelper {

    private final Logger log = LoggerFactory.getLogger(BaseUserHelper.class);
    @Autowired
    private MallRepository mallRepository;
    @Autowired
    private MerchantRepository merchantRepository;
    @Autowired
    private SysUserRoleRepository sysUserRoleRepository;
    @Autowired
    private SysPermissionRepository sysPermissionRepository;
    @Autowired
    private SysRolePermissionRepository sysRolePermissionRepository;
    @Autowired
    private MerchantCertifyRepository merchantCertifyRepository;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MallMemberRepository mallMemberRepository;
    @Autowired
    private UserMallRepository userMallRepository;
    @Autowired
    private UserMerchantRepository userMerchantRepository;

    /**
     * 获取登录的token
     * @param userInfo
     * @return
     */
    public String getUserToken(UserInfo userInfo) {
        return DigestUtils.md5Hex(userInfo.getId() + userInfo.getUsername() + java.sql.Date.from(Instant.now()).getTime());
    }


    /**
     * 获取session
     *
     * @param request
     * @return
     */
    public UserInfoDto getSession(HttpServletRequest request) {
        UserInfoDto userInfoDto = (UserInfoDto) request.getSession().getAttribute(UserInfo.LOGIN_USER);
        if (userInfoDto != null) {
            String domain = RequestUtils.getDomain(request);

            if(StringUtils.isBlank(domain)){
                domain = request.getParameter("domain");
            }
//            log.info("======================>getSession domain:{}",domain);
            if (StringUtils.isNotBlank(domain)) {
                MallDto mallDto = userInfoDto.mallMap.get(domain);
                userInfoDto.mall = mallDto;
//                log.info("======================>getSession mallDto:{}",mallDto);
                String merchantId = request.getParameter("merchantId");
                if(StringUtils.isBlank(merchantId)){
                    merchantId = request.getHeader("merchantId");
                }
//                log.info("======================>getSession merchantId:{}",merchantId);
                if(StringUtils.isNotBlank(merchantId)) {
                    MerchantDto merchantDto = userInfoDto.merchantMap.get(domain+merchantId);
                    userInfoDto.merchant = merchantDto;
                    //如果mall为空，直接从merchant读取
                    if(merchantDto!=null) {//防止空指针
                        if (userInfoDto.mall == null) {
                            MallDto mall = new MallDto();
                            mall.setId(merchantDto.getMallId());
                            userInfoDto.mall = mall;
                        }
                    }
                }
            }
        }
        return userInfoDto;
    }

    /**
     * 设置session ,分两种情况 1:rockcent.com域名 2:自定义域名
     *
     * @param userInfo
     * @param request
     */
    public UserInfoDto setSession(UserInfo userInfo, HttpServletRequest request) {
        return this.setSession(userInfo, null, request);
    }

    /**
     * 设置session ,分两种情况 1:rockcent.com域名 2:自定义域名
     *
     * @param userInfo
     * @param request
     */
    public UserInfoDto setSession(UserInfo userInfo, UserAdmin userAdmin, HttpServletRequest request) {
        return this.setSession(userInfo, userAdmin, request, null, null);
    }


    /**
     * 设置session ,分两种情况 1:rockcent.com域名 2:自定义域名
     *
     * @param userInfo
     * @param request
     */
    public UserInfoDto setSession(UserInfo userInfo, UserAdmin userAdmin, HttpServletRequest request, UserMall userMall,UserMerchant userMerchant) {
        // 当user_token 为空时 , session 同样设置为空
        if (userInfo == null) {
            request.getSession().setAttribute(UserInfo.LOGIN_USER, userInfo);
            return null;
        }
        // 登录成功设置session
        UserInfoDto result = new UserInfoDto();
        if (userAdmin != null) {
            result.mallMap = new HashMap<>();
            result.merchantMap = new HashMap<>();
        } else {
            result.mallMap = new HashMap<>();
            result.merchantMap = new HashMap<>();
            result.permissionMap = new HashMap<>();
            result.setId(userInfo.getId());
            result.setUsername(userInfo.getUsername());
            result.setMobile(userInfo.getMobile());
            result.setEmail(userInfo.getEmail());

            //获取M端平台列表
            log.info("======================>userMall userId:{}",userInfo.getId());
            List<UserMall> userMalls = userMallRepository.findByUserIdAndAvailable(userInfo.getId(), Whether.YES);
            if(userMalls!=null && userMalls.size()>0) {
                List<Long> mallIdList = userMalls.stream().map(UserMall::getMallId).collect(Collectors.toList());
                log.info("======================>userMall mallIds:{}",mallIdList);
                List<Mall> mallList = mallRepository.findByIdIn(mallIdList);
                if (mallList == null || mallList.size() == 0) {
                    mallList = new ArrayList<>();
                }
                mallList.forEach(mall -> {
                    MallDto mallDto = new MallDto();
                    if (mall.getAuditCertifyInfoStatus() != null) {
                        mallDto.setAuditCertifyInfo(mall.getAuditCertifyInfoStatus().toString());
                        if (MallAuditCertifyInfoStatusType.AUDIT_PASS == mall.getAuditCertifyInfoStatus()) {
                            MallMember mallMember = mallMemberRepository.findByMallIdAndIsDelete(mall.getId(), Whether.NO);
                            if (mallMember != null) {
                                mallDto.setMallMember(mallMember.getStatus().toString());
                                int surplusDay = DateUtils.compareDate(RDateUtils.date2String(DateUtils.getCurrentDate(), "yyyy-MM-dd"), RDateUtils.date2String(mallMember.getDateDisabled(), "yyyy-MM-dd"), 0);
                                mallDto.setProbationDay(surplusDay);
                            }
                        }
                    }
                    RBeanUtils.copyProperties(mall, mallDto);
                    String name = "";
                    if (StringUtils.isNotEmpty(mall.getCustomerPlatformDomain()) && mall.getOpenCustomDomain() != null && Whether.YES.equals(mall.getOpenCustomDomain())) {
                        name = mall.getCustomerPlatformDomain();
                    } else {
                        name = mall.getHostname();
                    }
                    if (!result.mallMap.containsKey(name)) {
                        result.mallMap.put(name, mallDto);
                    }
                    //平台信息
                    MallMerchantDto mallMerchantDto = new MallMerchantDto();
                    mallMerchantDto.setMallLogoPath(mall.getLogoSmallPicture());
                    mallMerchantDto.setMallBigLogoPath(mall.getLogoBigPicture());
                    mallMerchantDto.setMallName(mall.getName());
                    mallMerchantDto.setMallId(mall.getId());
                    mallMerchantDto.setMallUrl(String.format("http://%s/mall_new/mobile_banner", name));
                    List<MallMerchantDto> mallMerchantDtos = result.permissionMap.computeIfAbsent(name, k -> new ArrayList<>());
                    mallMerchantDtos.add(mallMerchantDto);
                });
            }
            //获取B端平台列表
//            log.info("======================>userMerchant userId:{}",userInfo.getId());
            List<UserMerchant> userMerchants = userMerchantRepository.findByUserIdAndAvailable(userInfo.getId(), Whether.YES);
//            log.info("======================>userMerchants:{}",userMerchants);
            if(userMerchants!=null && userMerchants.size()>0) {
                for(UserMerchant um:userMerchants) {
                    MerchantDto merchantDto = new MerchantDto();
                    Merchant merchant = merchantRepository.findOne(um.getMerchantId());
                    Mall mall = mallRepository.findById(um.getMallId());
                    if(merchant==null || mall==null) {
                        continue;
                    }
                    RBeanUtils.copyProperties(merchant, merchantDto);
                    String hostname = "";
                    if (StringUtils.isNotEmpty(mall.getCustomerPlatformDomain()) && mall.getOpenCustomDomain() != null && Whether.YES.equals(mall.getOpenCustomDomain())) {
                        hostname = mall.getCustomerPlatformDomain();
                    } else {
                        hostname = mall.getHostname();
                    }
                    try {
                        if (MerchantStatus.PROBATION == merchant.getStatus()) {//试用期有效天数
                            Date now = new Date();
                            Date dateDisabled = merchant.getDateDisabled();
                            if (dateDisabled != null) {
                                int expiredDays =1000; //DateUtils.daysBetween(now, dateDisabled);
                                merchantDto.setExpiredDays(expiredDays);
                            }
                        }
                    } catch(Exception e) {
                    }
                    // 商家认证公司名称 企业认证 个人认证
                    MerchantCertify merchantCertify = merchantCertifyRepository.findByMerchantIdAndMallId(merchant.getId(), mall.getId());
                    if (merchantCertify != null) {
                        if (CertifyType.COMPANY == merchantCertify.getType()) {
                            merchantDto.setCompanyName(merchantCertify.getCompanyName());
                        }
                        if (CertifyType.PERSONAL == merchantCertify.getType()) {
                            merchantDto.setCompanyName(merchantCertify.getRealName());
                        }
                    }
                    // 分销协议默认true
                    merchantDto.setSaleProtocolStatus(true);
                    result.merchantMap.put(hostname+merchant.getId(), merchantDto);
                    MallMerchantDto mallMerchantDto = new MallMerchantDto();
                    mallMerchantDto.setMallLogoPath(mall.getLogoSmallPicture());
                    mallMerchantDto.setMallBigLogoPath(mall.getLogoBigPicture());
                    mallMerchantDto.setMallName(mall.getName());
                    mallMerchantDto.setMallId(mall.getId());
                    mallMerchantDto.setMerchantId(merchant.getId());
                    mallMerchantDto.setMerchantName(merchant.getName());
                    mallMerchantDto.setCustomerPlatformDomain(mall.getCustomerPlatformDomain());
                    mallMerchantDto.setServiceTelephone(mall.getServiceTelephone());
                    mallMerchantDto.setOnlineQq(mall.getOnlineQq());
                    mallMerchantDto.setMerchantUrl(String.format("http://%s/business/merchant/index", hostname));
                    List<MallMerchantDto> mallMerchantDtoList = result.permissionMap.computeIfAbsent(hostname, k -> new ArrayList<>());
                    mallMerchantDtoList.add(mallMerchantDto);
                }
            }
        }

        String userToken = this.getUserToken(userInfo);
        result.setUserToken(userToken);

        redisTemplate.boundValueOps(UserInfo.REDIS_USER_TOKEN_PREFIX + userToken).set(userInfo.getId().toString());
        Long userTokenTimer = 30 * 24 * 60 * 60L; // 30天 生命周期
        redisTemplate.expire(UserInfo.REDIS_USER_TOKEN_PREFIX + userToken, userTokenTimer, TimeUnit.SECONDS);

        request.getSession().setAttribute(UserInfo.LOGIN_USER, result);
        return result;
    }


}
